CODE 74. Spiral Matrix II

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/11/16/2013-11-16-CODE 74 Spiral Matrix II/

访问原文「CODE 74. Spiral Matrix II

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix: [
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public int[][] generateMatrix(int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
int[][] matrix = new int[n][n];
int number = 1;
int halfCol = (n - 1) / 2;
int halfRow = (n - 1) / 2;
int col = 0;
int row = 0;
while (row <= halfRow && col <= halfCol) {
for (int i = col; i < n - col; i++) {
matrix[row][i] = number++;
}
for (int i = row + 1; i < n - row; i++) {
matrix[i][n - col - 1] = number++;
}
if (row != n - row - 1) {
for (int i = n - col - 2; i >= col; i--) {
matrix[n - row - 1][i] = number++;
}
}
if (col != n - col - 1) {
for (int i = n - row - 2; i >= row + 1; i--) {
matrix[i][col] = number++;
}
}
row++;
col++;
}
return matrix;
}
Jerky Lu wechat
欢迎加入微信公众号